<template>
  <div class="group-list">
    <BasicTable @register="registerTable">
      <template #headerTop>
        <div class="text-lg font-bold my-2"> 设备组 </div>
      </template>
      <template #tableTitle>
        <div class="space-x-2">
          <a-button type="primary" @click="handleForm({})">
            <Icon icon="i-fluent:add-12-filled" /> 新增设备组
          </a-button>
          <a-input
            v-model:value="searchParam.textSearch"
            placeholder="输入搜索内容"
            allow-clear
            @change="reload"
            style="width: 240px"
          >
            <template #suffix>
              <icon icon="ant-design:search-outlined" />
            </template>
          </a-input>
        </div>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleDetail({ ...record })" :title="record.name">
          {{ record.name }}
        </a>
      </template>
      <template #deviceCount="{ record }">
        <Tag color="blue">{{ record.deviceCount }}</Tag>
      </template>
    </BasicTable>
    <InputForm @register="registerFormModal" @success="handleSuccess" />
    <ManageDevices @register="registerManageDevicesModal" @success="handleSuccess" />
    <DetailDrawer
      @register="registerDetailDrawer"
      @edit="handleDrawerEdit"
      @delete="handleDrawerDelete"
      @manage-devices="handleDrawerManageDevices"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTbGroupList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, reactive, ref } from 'vue';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { Icon } from '/@/components/Icon';
  import { Tag } from 'ant-design-vue';
  import InputForm from './groupForm.vue';
  import ManageDevices from './manageDevices.vue';
  import DetailDrawer from './detail.vue';
  import { getEntityGroupList, deleteEntityGroup } from '/@/api/tb/group';
  import type { Recordable } from '/@/types';

  const { createConfirm, showMessage } = useMessage();

  const searchParam = reactive({
    textSearch: '',
  });

  const tableColumns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      align: 'left',
      fixed: 'left',
      slot: 'firstColumn',
      ellipsis: false,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      align: 'left',
      ellipsis: false,
    },
    {
      title: '设备数量',
      dataIndex: 'deviceCount',
      key: 'deviceCount',
      width: 120,
      align: 'center',
      slot: 'deviceCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      format: 'date|YYYY-MM-DD HH:mm:ss',
      sorter: true,
      width: 160,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 200,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:apartment-outlined',
        title: '管理设备',
        onClick: handleManageDevices.bind(this, { ...record }),
      },
      {
        icon: 'ant-design:edit-outlined',
        title: '编辑',
        onClick: handleForm.bind(this, { ...record }),
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: '删除设备组',
        onClick: handleDelete.bind(this, { ...record }),
      },
    ],
  };

  const [registerFormModal, { openModal: openFormModal }] = useModal();
  const [registerManageDevicesModal, { openModal: openManageDevicesModal }] = useModal();
  const [registerDetailDrawer, { openDrawer: openDetailDrawer, closeDrawer: closeDetailDrawer, getOpen: isDetailOpen }] = useDrawer();

  const currentDetailRecord = ref<Recordable | null>(null);
  const [registerTable, { reload }] = useTable({
    rowKey: (record) => record.id.id,
    api: getEntityGroupList,
    beforeFetch: wrapFetchParams,
    defSort: { sortProperty: 'createdTime', sortOrder: 'DESC' },
    columns: tableColumns,
    actionColumn: actionColumn,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
  });

  function wrapFetchParams(param: any) {
    return {
      ...param,
      textSearch: searchParam.textSearch,
    };
  }

  // 模拟数据接口
  async function fetchGroupList(param: any) {
    // 模拟初始化数据
    const mockData = [
      {
        id: '1',
        name: '智能家居设备组',
        description: '包含所有智能家居相关设备',
        deviceCount: 15,
        createdTime: new Date('2024-01-15 10:30:00').getTime(),
      },
      {
        id: '2',
        name: '工业传感器组',
        description: '工业现场传感器设备集合',
        deviceCount: 28,
        createdTime: new Date('2024-02-20 14:20:00').getTime(),
      },
      {
        id: '3',
        name: '能源监测组',
        description: '能源消耗监测设备',
        deviceCount: 12,
        createdTime: new Date('2024-03-10 09:15:00').getTime(),
      },
      {
        id: '4',
        name: '环境监控组',
        description: '环境参数监控设备',
        deviceCount: 8,
        createdTime: new Date('2024-04-05 16:45:00').getTime(),
      },
      {
        id: '5',
        name: '安防设备组',
        description: '安全防护相关设备',
        deviceCount: 20,
        createdTime: new Date('2024-05-12 11:00:00').getTime(),
      },
    ];

    // 模拟搜索过滤
    let filteredData = mockData;
    if (searchParam.textSearch) {
      filteredData = mockData.filter(
        (item) => item.name.includes(searchParam.textSearch) || item.description.includes(searchParam.textSearch),
      );
    }

    // 模拟排序
    if (param.sortProperty) {
      filteredData.sort((a, b) => {
        const aValue = a[param.sortProperty];
        const bValue = b[param.sortProperty];
        if (param.sortOrder === 'ASC') {
          return aValue > bValue ? 1 : -1;
        } else {
          return aValue < bValue ? 1 : -1;
        }
      });
    }

    // 模拟分页
    const pageSize = param.pageSize || 10;
    const page = param.page || 0;
    const start = page * pageSize;
    const end = start + pageSize;
    const pageData = filteredData.slice(start, end);

    // 返回标准格式
    return Promise.resolve({
      data: pageData,
      totalElements: filteredData.length,
      totalPages: Math.ceil(filteredData.length / pageSize),
    });
  }

  function handleForm(record: Recordable) {
    openFormModal(true, record);
  }

  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'error',
      title: `确定删除设备组[${record.name}]吗？`,
      content: '删除后设备组及其关联配置将无法恢复。',
      centered: false,
      okText: '删除',
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        const deviceGroupId = record.id?.id ?? record.id;
        if (!deviceGroupId) {
          showMessage('删除设备组失败：缺少设备组 ID', 'error');
          return;
        }
        try {
          await deleteEntityGroup(deviceGroupId);
          showMessage(`设备组 [${record.name}] 已成功删除`, 'success');
          if (currentDetailRecord.value) {
            const currentId = currentDetailRecord.value?.id?.id ?? currentDetailRecord.value?.id;
            if (currentId === deviceGroupId) {
              currentDetailRecord.value = null;
              closeDetailDrawer();
            }
          }
          reload();
        } catch (error: any) {
          const errorMessage = error?.message || error?.data?.message || '未知错误';
          showMessage(`删除设备组失败: ${errorMessage}`, 'error');
        }
      },
    });
  }

  function handleSuccess(payload?: Recordable) {
    reload();
    if (payload) {
      const payloadId = payload?.id?.id ?? payload?.id ?? payload?.groupId?.id ?? payload?.groupId;
      const currentId = currentDetailRecord.value?.id?.id ?? currentDetailRecord.value?.id;
      if (payloadId && currentId && payloadId === currentId) {
        currentDetailRecord.value = { ...currentDetailRecord.value, ...payload };
      }
    }
    if (isDetailOpen.value && currentDetailRecord.value) {
      openDetailDrawer(true, { ...currentDetailRecord.value });
    }
  }

  function handleManageDevices(record: Recordable) {
    currentDetailRecord.value = { ...record };
    openManageDevicesModal(true, record);
  }

  function handleDetail(record: Recordable) {
    currentDetailRecord.value = { ...record };
    openDetailDrawer(true, record);
  }

  function handleDrawerEdit(record: Recordable) {
    closeDetailDrawer();
    handleForm(record);
  }

  function handleDrawerDelete(record: Recordable) {
    closeDetailDrawer();
    currentDetailRecord.value = null;
    handleDelete(record);
  }

  function handleDrawerManageDevices(record: Recordable) {
    currentDetailRecord.value = { ...record };
    handleManageDevices(record);
  }
</script>
<style lang="less">
  .group-list {
  }
</style>
